var WebSocket = require('ws');
var url = require('url');
var _ = require('lodash')
var read = require('hy5b/backend/read')
var path = require('path')
var moment = require('moment')
var auto = require('hy5b/auto')
var apiTest = require('hy5b/auto/api-test')

var TMP_PATH = path.resolve(__dirname, '../../../../tmp');
var USE_TEMP_DATA = 0

var steps = {}

var TIME_FORMATE = '___HH_mm_ss_SSS___'

function creator(server, urlPath) {
  const wss = new WebSocket.Server({ noServer: true });
 
  wss.on('connection', function connection(ws) {
    ws.on('close', function(code, message) {
      console.warn('[websocket: closed]', code, message)
    })
    
    ws.on('message',function incoming(message) {
      if (message === '1') {
        ws.send('2');
        return;
      }
      //{
      //  "listener":"add",
      //  "id":"bdb24f053f864cca9300d4b1c608271c",
      //  "sequence":"e416c3e3c19e4c01acdd931194ca9f88bdb24f053f864cca9300d4b1c608271c_1567061414522",
      //  "filterStr":{"requiredFields":["id","alert"]},
      //  "windowId":"0568b955a137452e956e9d5768717ca9",
      //  "widgetType":"chart",
      //  "mode":"edit",
      //  "chartType":"bar",
      //  "windowName":"领航员"
      //}
      const option = JSON.parse(message);
      const dataSetId = option.id;
      const sequenceId = option.sequence
      
      let obj = {}
      
      if (dataSetId === 'bdb24f053f864cca9300d4b1c608271c') { //MOCK统一可用，勿删
        obj.collection = require('../../api/data/_mock/data').data.collection;
      } else if (dataSetId === '994bb8ed7f1042898a0ddeafdf13b52a') {
        obj.collection = require('./data/静态数据-节点.json')
      } else if (dataSetId === 'cb6afe3c5c5644a69355dc872568df34') {
        obj.collection = require('./data/静态数据-链路.json')
      } else if (dataSetId === '17cef3e03ff241f89e808265bfa3f90d') {
        obj.collection = apiTest.gis().data;
      } else if (dataSetId === 'storeset000000000000000000000000') {
        
        let objs = []
        const tpmTextPath = './data/show-data.txt'
        // const tpmTextPath = path.resolve(TMP_PATH, '2019/1021/ws.txt')
        read.eachLine(tpmTextPath, function(line) {
          if (line) {
            try {
              obj = { time: '' }
              obj.collection = JSON.parse(decodeURIComponent(line)).collection
            } catch (e) {
              console.log(e)
            }
            // _.each(obj.collection, (item) => {
              // item['MappingOf_Merchant_1'] = item['MappingOf_Merchant_4'];
              // item['ts'] = item['ts_start']
            // })
            obj.id = dataSetId;
            obj.sequence = sequenceId;
            obj.status = true
            
            objs.push(obj)
            
          }
        }).then(function(e) {
          var i = 0
          
          step2()
      
          function step2() {
            if (objs.length === 0) {

            } else if (i < objs.length) {
              // console.log('[websocket: emit2]', dataSetId, sequenceId, objs[i].collection.length)
              if (ws.readyState === WebSocket.OPEN) {
                let obj = objs[i]
                obj.time = moment().format(TIME_FORMATE)
                ws.send(encodeURIComponent(JSON.stringify(obj)));
              }
              i++;
              setTimeout(step2, 5000);
            } else {
              i = 0
              step2()
            }

          }
        })
        return
      } else if (option.listener === 'add') {
        obj.time = ''
        obj.collection = []
      } else if (option.listener === 'remove') {
        clearTimeout(steps[sequenceId])
      }
      
      if (_.isEmpty(obj)) {
        return
      }
      
      obj.id = dataSetId;
      obj.sequence = sequenceId;
      obj.status = true
      
      step()
      
      function step() {
        // steps[sequenceId] = setTimeout(step, 5000);
        
        if (ws.readyState === WebSocket.OPEN) {
          const factor = option.filterStr && option.filterStr.factor;
          const resource = option.filterStr && option.filterStr.resource;
          const requiredFields = option.filterStr && option.filterStr.requiredFields;

          if (_.isEmpty(obj.collection)) {
            
            if (resource && resource.length > 0) {
              obj.collection = _.map(resource, item => {
                let data = { resource: { id: item } }
                _.each(requiredFields, field => {
                  if (field !== 'resource') {
                    data[field] = _.random(1215, 1626)
                  }
                })
                return data;
              })
            } else if (factor && factor.length > 0) {
              const factorKey = factor[0].target.value
              const factorValues = factor[0].value
              obj.collection = _.map(factorValues, item => {
                let data = { [factorKey]: item }
                _.each(requiredFields, field => {
                  if (field !== factorKey) {
                    data[field] = _.random(1215, 1626)
                  }
                })
                return data;
              })
            } else if (!_.isEmpty(requiredFields)) {
              obj.collection = _.map([
                "DSBP01", "DSBP02", "DSBP03", "DSBP04",
                "DSBP05", "DSBP06", "DSBP07", "DSBP08",
                "DGBP03", "DGBP04", "DGBP05", "DGBP06"
              ], item => {
                let data = {}
                _.each(requiredFields, field => {
                  // data[field] = auto('@csentence(10, 25)')
                  data[field] = _.random(1215, 1626)
                })
                return data;
              })
            }
          } else {
            _.each(obj.collection, item => {
              item['ts'] = item['msTime']
              item['SUM_req_count_3'] = item['alertCount']
            })
          }

          // console.log('[websocket: emit]', dataSetId, sequenceId)
          obj.time = moment().format(TIME_FORMATE)
          ws.send(encodeURIComponent(JSON.stringify(obj)));
        }
      }
      
    });
  });

  server.on('upgrade', function upgrade(request, socket, head) {
    const pathname = url.parse(request.url).pathname;
    // console.log(request.url, pathname, urlPath);

    if (pathname === urlPath || _.include(pathname, urlPath)) {
      wss.handleUpgrade(request, socket, head, function done(ws) {
        console.log('[websocket: send connection]');
        wss.emit('connection', ws, request);
      });
    } else {
      socket.destroy();
    }
  });
}

module.exports = creator;
